package com.cssy.xxkj.attach.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONArray;
import com.cssy.base.web.BaseController;
import com.cssy.xxkj.attach.entity.AttachFileUploadDO;
import com.cssy.xxkj.attach.service.IAttachFileUploadService;
import com.cssy.xxkj.attach.util.CommConstants;
import com.cssy.xxkj.attach.util.JsonUtils;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.OutJsonGrid;

@Controller
@RequestMapping("/attach/upload")
public class FileUploadController extends BaseController<AttachFileUploadDO>{
	
	private static final Logger logger = Logger.getLogger(FileUploadController.class);
	
	private static final String CANFILEUPLOAD = "/xxkj/attach/upload/FileUploadManager";// 添加、修改、显示页面

	@Resource(name = "attachFileUploadService")
    private IAttachFileUploadService attachFileUploadService;
	
	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public String operationForm(HttpServletRequest request, String id,
			String flag, Model model) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			AttachFileUploadDO curAP, BindingResult result, Model model)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	
	@RequestMapping("/filedown")
	public void download(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		//传这2个参数比穿附件的id要好，不要请求数据库，增加数据的负载
		String diskPath = request.getParameter("diskPath");
		String fileName = request.getParameter("fileName");
		
		//方法一
		if(StringUtils.isNotBlank(diskPath)){
			String realPath = CommConstants.UPLOAD_BASE_DIR;
			realPath = realPath + "/" + diskPath;
			
			File file = new File(realPath);
			if(!file.exists()){
				throw new RuntimeException("文件未找到,请检查!");
			}
			
			response.setContentType("application/octet-stream;charset=utf-8");
        	response.setHeader("Content-disposition","attachment;filename="+fileName);
        	
        	OutputStream os = response.getOutputStream();
        	InputStream inputstream = new FileInputStream(file);
    		try{
    			byte[] buffer = new byte[1024*100];
    			int read_len = -1;
    			while((read_len = inputstream.read(buffer))!=-1){
    				os.write(buffer, 0, read_len);
    			}
    			os.flush();
    		}finally{
    			if(inputstream!=null){
    				inputstream.close();
    			}
    		}
		}
		
		/*//方法二
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			AttachFileUploadDO fileUploadDO = attachFileUploadService.findByPrimaryKey(id);
			String szFileName = fileUploadDO.getFileName();
			String realPath = CommConstants.UPLOAD_BASE_DIR;
			realPath = realPath + "/" + disPath;
			
			File file = new File(realPath);
			if(!file.exists()){
				throw new RuntimeException("文件未找到,请检查!");
			}
			
			response.setContentType("application/octet-stream;charset=utf-8");
        	response.setHeader("Content-disposition","attachment;filename="+szFileName);
        	
        	OutputStream os = response.getOutputStream();
        	InputStream inputstream = new FileInputStream(file);
    		try{
    			byte[] buffer = new byte[1024*100];
    			int read_len = -1;
    			while((read_len = inputstream.read(buffer))!=-1){
    				os.write(buffer, 0, read_len);
    			}
    			os.flush();
    		}finally{
    			if(inputstream!=null){
    				inputstream.close();
    			}
    		}
		}*/
	}
	
	@RequestMapping("/deleteFile")
	public void getClientBeanByNo(HttpServletResponse response,@RequestParam("attachFileId") String attachFileId){
		
		int count = attachFileUploadService.deleteFileUploadDO(attachFileId);
		
		Map<String,String> map = new HashMap<String,String>();
		
		if(count>0){
			map.put("isDel", "yes");
		}else{
			map.put("isDel", "no");
		}
		AjaxUtil.printJSonArr(response, JSONArray.toJSONString(map));
	}
	
	@RequestMapping("/canFileUploadManager")
	public String canFileUploadManager(HttpServletRequest request,Model model){
		String projectId = request.getParameter("projectId");
		model.addAttribute("projectId",projectId);
		return CANFILEUPLOAD;
	}
	
	@RequestMapping("/getCanFileUploadByProjectId")
	public void getCanFileUploadByProjectId(HttpServletRequest request,HttpServletResponse response,String projectId){
		
		if(StringUtils.isNotBlank(projectId)){
			Map<String,String> paramMap = new HashMap<String,String>();
			paramMap.put("projectId",projectId);
			paramMap.put("fileRelated",CommConstants.FILE_RELATED_YES);
			
			List<AttachFileUploadDO> fileUploads = attachFileUploadService.findAttachFileUploadDOs(paramMap);
			
			OutJsonGrid out = new OutJsonGrid(fileUploads);
			out.printJSon(response);
		}
	}
	
	@RequestMapping("/toSaveFileUpload")
	public String toSaveFileUpload(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("filename");
		if(file==null){
			logger.error("");
		}
		Map map = attachFileUploadService.saveTemp(multipartRequest, file, null, null, null);
		List list =  new ArrayList();
		list.add(map);
		response.setContentType("text/html; charset=utf-8");
		response.setHeader("Cache-Control","no-store");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		response.getWriter().write(JsonUtils.toJsonArray(list, new String[0]).toString());
		return null;
		
	}
}
